/**
 * 文档导航组件
 * Phase 1: 前端 MVP 使用
 * 
 * 功能：
 * - 树形分类导航
 * - 展开/折叠
 * - 当前文档高亮
 * - 文档计数
 */

import React, { useState, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { ChevronRight, ChevronDown, FileText, Folder, FolderOpen } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';

const DocNav = ({ categories = [], currentSlug }) => {
  const location = useLocation();
  const [expanded, setExpanded] = useState({});

  // 递归查找包含指定文档的分类路径
  const findCategoryPath = (categories, targetSlug) => {
    const search = (items, currentPath = []) => {
      for (const item of items) {
        // 检查当前分类的文档
        if (item.documents?.some(doc => doc.slug === targetSlug)) {
          return [...currentPath, item.id];
        }

        // 递归检查子分类
        if (item.children && item.children.length > 0) {
          const childPath = search(item.children, [...currentPath, item.id]);
          if (childPath) {
            return childPath;
          }
        }
      }
      return null;
    };

    return search(categories) || [];
  };

  // 自动展开包含当前文档的分类（支持无限层级）
  useEffect(() => {
    if (currentSlug && categories.length > 0) {
      const path = findCategoryPath(categories, currentSlug);

      // 将路径上的所有分类都设为展开状态
      const newExpanded = {};
      path.forEach(id => {
        newExpanded[id] = true;
      });

      setExpanded(newExpanded);
    }
  }, [currentSlug, categories]);

  // 切换展开/折叠
  const toggleExpand = (id) => {
    setExpanded(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };

  // 渲染文档列表
  const renderDocuments = (docs = [], level = 0) => {
    if (!docs || docs.length === 0) return null;

    return docs.map(doc => {
      const isActive = doc.slug === currentSlug ||
        location.pathname.includes(`/documentation/${doc.slug}`);

      // 根据层级计算缩进（每层 16px）
      const marginLeft = level * 16;

      return (
        <Link
          key={doc.id}
          to={`/documentation/${doc.slug}`}
          style={{ marginLeft: `${marginLeft}px` }}
          className={cn(
            "flex items-center gap-2 px-3 py-2 rounded-md text-sm transition-all",
            isActive
              ? "bg-primary/10 text-primary border-l-2 border-primary font-medium"
              : "text-foreground/70 hover:bg-accent hover:text-accent-foreground"
          )}
          title={doc.title}
        >
          <FileText className={cn("size-4 flex-shrink-0", isActive && "text-primary")} />
          <span className="flex-1 line-clamp-2 break-words text-sm">{doc.title}</span>
        </Link>
      );
    });
  };

  // 递归计算所有后代的文档数量
  const countAllDocs = (item) => {
    let count = item.documents?.length || 0;
    if (item.children) {
      item.children.forEach(child => {
        count += countAllDocs(child);
      });
    }
    return count;
  };

  // 渲染子分类（递归函数，支持无限层级）
  const renderChildren = (children = [], level = 1) => {
    if (!children || children.length === 0) return null;

    return children.map(child => {
      const isExpanded = expanded[child.id];
      const hasChildren = child.children && child.children.length > 0;
      const hasDocuments = child.documents && child.documents.length > 0;
      const documentCount = countAllDocs(child);

      // 根据层级计算缩进（每层 16px）
      const marginLeft = level * 16;

      return (
        <div key={child.id} style={{ marginLeft: `${marginLeft}px` }}>
          {/* 子分类标题 */}
          <div
            className={cn(
              "flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer transition-all",
              "text-foreground/80 hover:bg-accent hover:text-accent-foreground"
            )}
            onClick={() => (hasDocuments || hasChildren) && toggleExpand(child.id)}
            title={`${child.name} (${documentCount} 篇文档)`}
          >
            {/* 展开/折叠图标 */}
            {(hasDocuments || hasChildren) && (
              <span className="flex-shrink-0">
                {isExpanded ? (
                  <ChevronDown className="size-4 text-muted-foreground" />
                ) : (
                  <ChevronRight className="size-4 text-muted-foreground" />
                )}
              </span>
            )}

            {!hasDocuments && !hasChildren && <span className="w-4" />}

            {/* 文件夹图标 */}
            <span className="flex-shrink-0">
              {isExpanded ? (
                <FolderOpen className="size-4 text-primary" />
              ) : (
                <Folder className="size-4 text-muted-foreground" />
              )}
            </span>

            <span className="flex-1 text-sm font-medium line-clamp-2 break-words">{child.name}</span>

            {documentCount > 0 && (
              <Badge variant="secondary" className="text-xs flex-shrink-0 min-w-[24px] justify-center">
                {documentCount}
              </Badge>
            )}
          </div>

          {/* 展开的内容 */}
          {isExpanded && (
            <div className="mt-1 space-y-1">
              {/* 当前分类的文档和子分类同级显示 */}
              {hasDocuments && (
                <div className="space-y-1">
                  {renderDocuments(child.documents, level + 1)}
                </div>
              )}

              {/* 递归渲染子分类（关键：支持无限层级） */}
              {hasChildren && (
                <div className="space-y-1">
                  {renderChildren(child.children, level + 1)}
                </div>
              )}
            </div>
          )}
        </div>
      );
    });
  };

  // 渲染顶级分类
  const renderCategory = (category) => {
    const isExpanded = expanded[category.id];
    const hasChildren = category.children && category.children.length > 0;
    const hasDocuments = category.documents && category.documents.length > 0;
    const totalDocs = countAllDocs(category);

    return (
      <div key={category.id} className="mb-3">
        {/* 分类标题 */}
        <div
          className={cn(
            "flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer transition-all",
            "text-foreground font-medium hover:bg-accent hover:text-accent-foreground"
          )}
          onClick={() => toggleExpand(category.id)}
          title={`${category.name} (${totalDocs} 篇文档)`}
        >
          <span className="flex-shrink-0">
            {isExpanded ? (
              <ChevronDown className="size-4 text-muted-foreground" />
            ) : (
              <ChevronRight className="size-4 text-muted-foreground" />
            )}
          </span>

          <span className="flex-shrink-0">
            {isExpanded ? (
              <FolderOpen className="size-4 text-primary" />
            ) : (
              <Folder className="size-4 text-muted-foreground" />
            )}
          </span>

          <span className="flex-1 text-sm line-clamp-2 break-words">{category.name}</span>

          {totalDocs > 0 && (
            <Badge variant="secondary" className="text-xs flex-shrink-0 min-w-[24px] justify-center">
              {totalDocs}
            </Badge>
          )}
        </div>

        {/* 展开的内容 */}
        {isExpanded && (
          <div className="mt-2 space-y-1">
            {/* 当前分类的文档 */}
            {hasDocuments && (
              <div className="space-y-1">
                {renderDocuments(category.documents, 1)}
              </div>
            )}

            {/* 子分类 */}
            {hasChildren && (
              <div className="space-y-1">
                {renderChildren(category.children, 1)}
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  if (!categories || categories.length === 0) {
    return (
      <div className="p-8 text-center text-muted-foreground">
        <Folder className="size-12 mx-auto mb-2 opacity-50" />
        <p className="text-sm">暂无文档分类</p>
      </div>
    );
  }

  // 计算所有文档总数（递归统计）
  const totalDocCount = categories.reduce((sum, cat) => sum + countAllDocs(cat), 0);

  return (
    <div className="h-screen flex flex-col">
      {/* 标题（固定顶部，不滚动） */}
      <div className="flex-shrink-0 p-4 pb-2 border-b">
        <h2 className="text-base font-semibold text-foreground px-3">
          文档导航
        </h2>
        <p className="text-xs text-muted-foreground mt-1 px-3">
          {totalDocCount} 篇文档
        </p>
      </div>

      {/* 分类列表（独立滚动区域，占满剩余空间） */}
      <ScrollArea className="flex-1">
        <nav className="p-4 space-y-1">
          {categories.map(renderCategory)}
        </nav>
      </ScrollArea>
    </div>
  );
};

export default DocNav;

